<template>
  <el-drawer v-loading="data.loading" v-model="data.show" size="500px">
    <template #header>
      <h4>填报信息</h4>
    </template>
    <template #default>
      <el-row>
        <el-col :span="24">
          <el-button-group class="mb-4">
            <el-button type="default" @click="data.tabValue = '基础信息'" :class="{ 'button-select': data.tabValue === '基础信息' }">基础信息</el-button>
            <el-button v-if="data.form.formConfigKpi" type="default" @click="data.tabValue = '指标信息'" :class="{ 'button-select': data.tabValue === '指标信息' }">指标信息</el-button>
          </el-button-group>
          <el-divider />
          <EBuilder style="overflow-y: auto;" v-show="data.tabValue === '基础信息'" ref="designerRef" :pageSchema="pageSchema" :formData="data.formData" />
          <EBuilder style="overflow-y: auto;" v-show="data.tabValue === '指标信息'" ref="kpiDesignerRef" :pageSchema="pageSchemaKpi" :formData="data.formDataKpi" />
        </el-col>
      </el-row>


    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancelClick">取消</el-button>
        <el-button v-if="data.type === 'add'" type="primary" @click.stop="updateClick"> 提交</el-button>
        <el-button v-if="data.type === 'update'" type="primary" @click.stop="updateClick"> 更新</el-button>
        <el-button v-if="data.type === 'examine'" type="primary" @click.stop="examineClick"> 审核通过</el-button>
      </div>
    </template>
  </el-drawer>

</template>
<script setup name="SubCommunity_view" lang="ts">
// 获取当前Vue组件实例
const { proxy } = getCurrentInstance()
const emit = defineEmits(["getList"])
// 导入Vue相关函数
import { ref, reactive, toRefs, getCurrentInstance, nextTick } from 'vue';
import { getFormconfig } from "@/api/system/formconfig"
import { EBuilder, PageSchema } from "epic-designer";
import { saveData, getSubCommunity, updateSubCommunity } from "@/api/system/subCommunity"
import { getCommunity, updateCommunity } from "@/api/system/community"
import { getStreetCommunity, updateStreetCommunity } from "@/api/system/streetCommunity"
import { getDistrictCounty, updateDistrictCounty } from "@/api/system/districtCounty"
import { getResidentialBuildings, updateResidentialBuildings } from "@/api/system/residentialBuildings"

const pageSchema = ref<PageSchema>({ schemas: [] });
const pageSchemaKpi = ref<PageSchema>({ schemas: [] });
// 获取表单设计器组件引用
const designerRef = ref<InstanceType<typeof EBuilder>>();
const kpiDesignerRef = ref<InstanceType<typeof EBuilder>>();
// const designerRef = ref(null)
const data = reactive({
  formData: {},
  formDataKpi: {},
  loading: false,
  show: false,
  type: '',
  tabValue: '基础信息',
  form: {
    buildingCount: '',
    city: '',
    communityCount: '',
    createBy: '',
    createTime: '',
    delFlag: '',
    district: '',
    formConfigId: '',
    formConfigType: '',
    formDataId: '',
    formDataName: '',
    id: '',
    name: '',
    province: '',
    state: '1',
    subCommunityCount: '',
    updateBy: '',
    updateTime: '',
    administrativeRegion: '',
    administrativeRegionLevel: '',
    formData: '',

    year: 0,
    formConfig: '',
    formDataKpi: '',
    formConfigKpiId: '',
    formConfigKpi: '',
    formDataNameKpi: '',
    formDataKpiId: '',

  },
})
const { formData } = toRefs(data)
/** 获取表单配置JSON */
function getFormConfigJson(ID: string, kpiId: String) {
  data.loading = true

  if (kpiDesignerRef.value) {
    //基本填报表单
    getFormconfig(ID).then((response: any) => {
      if (response.data) {
        console.log("getFormconfig", response.data)
        // 设置表单设计器json数据
        pageSchema.value = JSON.parse(response.data.formJson);
        data.form.year = response.data.year
        //数据表id 表单生成的数据库表名本次填报的数据id
        data.form.formDataId = response.data.formDataId
        // 表单配置id
        data.form.formConfigId = response.data.formConfigId
        // 表单类型
        data.form.formConfigType = response.data.formType
        //数据表名称 表单生成的数据库表名
        data.form.formDataName = response.data.formCode
        data.form.name = response.data.formName
        data.form.administrativeRegionLevel = response.data.adminLevel
        // 行政区域
        if (response.data.adminCodeOne) {
          data.form.province = response.data.adminCodeOne
          data.form.administrativeRegion = response.data.adminCodeOne
        }
        if (response.data.adminCodeTwo) {
          data.form.city = response.data.adminCodeTwo
          data.form.administrativeRegion = response.data.adminCodeTwo
        }
        if (response.data.adminCodeThree) {
          data.form.district = response.data.adminCodeThree
          data.form.administrativeRegion = response.data.adminCodeThree
        }
        if (response.data.adminCodeOther) {
          data.form.administrativeRegion = response.data.adminCodeOther
          data.form.administrativeRegion = response.data.administrativeRegion
        }

      }



    }).finally(() => {
      // 取消加载状态
      data.loading = false
    })
    if (kpiId) {
      getFormconfig(kpiId).then((response: any) => {
        if (response.data) {
          console.log("getKpiFormconfig", response.data)
          // 设置表单设计器json数据
          pageSchemaKpi.value = JSON.parse(response.data.formJson);

          //数据表id 表单生成的数据库表名本次填报的数据id
          data.form.formDataKpiId = response.data.formDataId
          // 表单配置id
          data.form.formConfigKpiId = response.data.formConfigId

          //数据表名称 表单生成的数据库表名
          data.form.formDataNameKpi = response.data.formCode


        }



      }).finally(() => {
        // 取消加载状态
        data.loading = false
      })
    }

  }
}

/** 取消按钮 */
function cancelClick() {

  // 重置表单数据
  data.form = {
    buildingCount: '',
    city: '',
    communityCount: '',
    createBy: '',
    createTime: '',
    delFlag: '',
    district: '',

    id: '',
    name: '',
    province: '',
    state: '1',
    subCommunityCount: '',
    updateBy: '',
    updateTime: '',
    administrativeRegion: '',
    administrativeRegionLevel: '',
    formData: '',
    year: 0,
    formConfig: '',
    formConfigId: '',
    formConfigType: '',
    formDataId: '',
    formDataName: '',
    formConfigKpiId: '',
    formConfigKpi: '',
    formDataKpi: '',
    formDataNameKpi: '',
    formDataKpiId: '',

  }
  data.show = false
  // 调用父级getList方法
  emit('getList')

}
async function examineClick() {
  if (data.form.state === '1') {
    data.form.state = '2'
    data.loading = true
    //基本信息
    data.form.formConfig = JSON.stringify(pageSchema.value)
    data.form.formData = JSON.stringify(data.formData)
    //指标信息
    data.form.formConfigKpi = JSON.stringify(pageSchemaKpi.value)
    data.form.formDataKpi = JSON.stringify(data.formDataKpi)

    //判断表单类型
    if (data.form.administrativeRegionLevel === 'form_type_street') {
      //街道社区详情加载
      updateStreetCommunity(data.form).then((response: any) => {
        if (response) {
          proxy.$message({
            message: '审核通过',
            type: 'success'
          })
          cancelClick()
        }
      }).finally(() => {
        // 取消加载状态
        data.loading = false
        console.log('加载状态', data.form)
      })

    } else if (data.form.administrativeRegionLevel === 'form_type_community') {
      updateCommunity(data.form).then((response: any) => {
        if (response) {
          proxy.$message({
            message: '审核通过',
            type: 'success'
          })
        }
      }).finally(() => {
        // 取消加载状态
        data.loading = false
        console.log('加载状态', data.form)
      })

    } else if (data.form.administrativeRegionLevel === 'form_type_residential') {
      updateSubCommunity(data.form).then((response: any) => {
        if (response) {
          proxy.$message({
            message: '审核通过',
            type: 'success'
          })
        }
      }).finally(() => {
        // 取消加载状态
        data.loading = false
        console.log('加载状态', data.form)
      })

    } else if (data.form.administrativeRegionLevel === 'form_type_county') {

      updateDistrictCounty(data.form).then((response: any) => {
        if (response) {
          proxy.$message({
            message: '审核通过',
            type: 'success'
          })
        }
      }).finally(() => {
        // 取消加载状态
        data.loading = false
        console.log('加载状态', data.form)
      })
    } else if (data.form.administrativeRegionLevel === 'form_type_housing') {
      updateResidentialBuildings(data.form).then((response: any) => {
        if (response) {
          proxy.$message({
            message: '审核通过',
            type: 'success'
          })
        }
      }).finally(() => {
        // 取消加载状态
        data.loading = false
        console.log('加载状态', data.form)
      })

    }

  }

}
/** 更新按钮 */
async function updateClick() {
  if (designerRef.value) {
    // 获取表单数据

    data.formData = { ...(await designerRef.value.validate()) }
    console.log('获取表单数据', data.formData)
    //基本信息
    data.form.formConfig = JSON.stringify(pageSchema.value)
    data.form.formData = JSON.stringify(data.formData)
    //指标信息
    data.form.formConfigKpi = JSON.stringify(pageSchemaKpi.value)
    data.form.formDataKpi = JSON.stringify(data.formDataKpi)



    if (data.type === 'add') {
      data.form.delFlag = '0'
      data.form.state = '1'
    }

    console.log(data.form)


    data.loading = true
    // 提交表单数据到后端
    saveData(data.form).then((response: any) => {
      if (response.data) {
        proxy.$message({
          message: '保存成功',
          type: 'success'
        })
        cancelClick()
      }
    }).catch((error: any) => {
      proxy.$message({
        message: error.message,
        type: 'error'
      })
    }).finally(() => {
      // 取消加载状态
      cancelClick()

    })
  }
}
/**打开页面 */
const onOpen = async (row: any, type: string) => {
  data.show = true
  console.log("onOpen", row)
  nextTick(() => {
    data.type = type
    //判断打开页面类型
    if (type === 'view') {
      // 初始化表单数据
      data.form = JSON.parse(JSON.stringify(row));
      pageSchema.value = JSON.parse(data.form.formConfig);
      data.formData = JSON.parse(data.form.formData)
    }
    else if (type === 'examine') {
      // 审核
      data.loading = true
      loadData(row)
    } else if (type === 'add') {
      // 添加
      // 初始化样式 街道
      getFormConfigJson('6', '')

    } else if (type === 'update') {
      // 更新
      data.loading = true
      loadData(row)
    }
  })
}

/**
 *  详情加载
 */
function loadData(row: any) {
  //判断表单类型
  if (row.administrativeRegionLevel === 'form_type_street') {
    //街道社区详情加载
    getStreetCommunity(row.id).then((response: any) => {
      if (response.data) {

        data.form = JSON.parse(JSON.stringify(response.data));
        pageSchema.value = JSON.parse(data.form.formConfig);
        data.formData = JSON.parse(data.form.formData)
        //指标信息
        pageSchemaKpi.value = JSON.parse(data.form.formConfigKpi)
        data.formDataKpi = JSON.parse(data.form.formDataKpi)
      }
    }).finally(() => {
      // 取消加载状态
      data.loading = false
      console.log('加载状态', data.form)
    })

  } else if (row.administrativeRegionLevel === 'form_type_community') {
    getCommunity(row.id).then((response: any) => {
      if (response.data) {

        data.form = JSON.parse(JSON.stringify(response.data));
        pageSchema.value = JSON.parse(data.form.formConfig);
        data.formData = JSON.parse(data.form.formData)
        //指标信息
        pageSchemaKpi.value = JSON.parse(data.form.formConfigKpi)
        data.formDataKpi = JSON.parse(data.form.formDataKpi)
      }
    }).finally(() => {
      // 取消加载状态
      data.loading = false
      console.log('加载状态', data.form)
    })

  } else if (row.administrativeRegionLevel === 'form_type_residential') {
    getSubCommunity(row.id).then((response: any) => {
      if (response.data) {

        data.form = JSON.parse(JSON.stringify(response.data));
        pageSchema.value = JSON.parse(data.form.formConfig);
        data.formData = JSON.parse(data.form.formData)
        //指标信息
        pageSchemaKpi.value = JSON.parse(data.form.formConfigKpi)
        data.formDataKpi = JSON.parse(data.form.formDataKpi)
      }
    }).finally(() => {
      // 取消加载状态
      data.loading = false
      console.log('加载状态', data.form)
    })

  } else if (row.administrativeRegionLevel === 'form_type_county') {

    getDistrictCounty(row.id).then((response: any) => {
      if (response.data) {

        data.form = JSON.parse(JSON.stringify(response.data));
        pageSchema.value = JSON.parse(data.form.formConfig);
        data.formData = JSON.parse(data.form.formData)
        //指标信息
        pageSchemaKpi.value = JSON.parse(data.form.formConfigKpi)
        data.formDataKpi = JSON.parse(data.form.formDataKpi)
      }
    }).finally(() => {
      // 取消加载状态
      data.loading = false
      console.log('加载状态', data.form)
    })
  } else if (row.administrativeRegionLevel === 'form_type_housing') {
    getResidentialBuildings(row.id).then((response: any) => {
      if (response.data) {

        data.form = JSON.parse(JSON.stringify(response.data));
        pageSchema.value = JSON.parse(data.form.formConfig);
        data.formData = JSON.parse(data.form.formData)
        //指标信息
        pageSchemaKpi.value = JSON.parse(data.form.formConfigKpi)
        data.formDataKpi = JSON.parse(data.form.formDataKpi)
      }
    }).finally(() => {
      // 取消加载状态
      data.loading = false
      console.log('加载状态', data.form)
    })

  }

}

defineExpose({
  onOpen
})
</script>
<style scoped lang="scss">
.el-drawer__body {
  flex: 1;
  overflow: none !important;
  padding: var(--el-drawer-padding-primary);
}

.button-select {
  background-color: var(--el-button-hover-bg-color);
  border-color: var(--el-button-hover-border-color);
  color: var(--el-button-hover-text-color);
  outline: none;
}
</style>